require 'family_tree_api/person/assertions/person'
require 'family_tree_api/person/assertions/date'
require 'family_tree_api/person/assertions/place'

module FamilyTreeApi
  module Person
    module Assertion
      
      class Fact < Base
        attr_accessor :scope, :type, :title, :date, :place, :spouse, :parent, :child, :detail
        
        def to_xml
          e = super
          e.add_attribute('type', @type)
          e.add_attribute('scope', @scope)
          e.add_element(@date.to_xml) if @date
          e.add_element('detail').add_text(@detail) if @detail
          e.add_element(@spouse.to_xml) if @spouse
          e.add_element(@parent.to_xml) if @parent
          e.add_element(@child.to_xml) if @child
          e
        end
        
        def self.new_parent(parent_ref, options = 'Biological')
          if options.is_a? String
            detail = options
            options = {}
            options[:detail] = detail
          else
            options[:detail] ||= 'Biological'
          end
          f = self.new
          f.type = 'Lineage'
          f.scope = 'parent-child'
          f.detail = options[:detail]
          f.tempId = options[:tempId] if options[:tempId]
          f.parent = FamilyTreeApi::Person::Assertion::Parent.new
          f.parent.ref = parent_ref
          f
        end
        
        def self.new_child(child_ref, options = 'Biological')
          if options.is_a? String
            detail = options
            options = {}
            options[:detail] = detail
          else
            options[:detail] ||= 'Biological'
          end
          f = self.new
          f.type = 'Lineage'
          f.scope = 'parent-child'
          f.detail = options[:detail]
          f.tempId = options[:tempId] if options[:tempId]
          f.child = FamilyTreeApi::Person::Assertion::Child.new
          f.child.ref = child_ref
          f
        end
        
        def self.parse(fact_element)
          fact = self.new
          fact.parse_attributes(fact_element)
          fact.scope = fact_element.attributes["scope"]
          fact.type = fact_element.attributes["type"]
          fact_element.each do |e|
            case e.name
            when 'detail'
              fact.detail = e.content
            when 'date'
              fact.date = Assertion::Date.parse(e)
            when 'place'
              fact.place = Assertion::Place.parse(e)
            when 'spouse'
              fact.spouse = Assertion::Spouse.parse(e)
            when 'parent'
              fact.parent = Assertion::Parent.parse(e)
            when 'child'
              fact.child = Assertion::Child.parse(e)
            end
          end
          fact
        end
      end
      
    end
  end
end
